<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close @closed="$emit('closed')">
		<sc-form ref="dialogForm" :disabled="mode==='show'" :config="config" v-model="form" :loading="loading"
				 :select-on-change="onSelected"/>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			config: {},
			mode: "add",
			titleMap: {
				add: '新增',
				edit: '编辑',
				show: '查看'
			},
			visible: false,
			loading: false,
			isSaveing: false,
			//表单数据
			form: {},
			//所需数据选项
			groups: [],
			groupsProps: {
				value: "id",
				emitPath: false,
				checkStrictly: true
			}
		}
	},
	updated() {

		// this.$refs.dialogForm.select.$on('change', this.onSelected);
	},
	mounted() {
		//模拟请求延迟, 配置参数和form值并无顺序要求，可同时请求
		this.config = {
			labelWidth: '60px',
			labelPosition: 'right',
			size: 'medium',
			formItems: [
				{
					label: "交易人信息",
					component: "title",
				},
				{
					label: "姓名",
					name: "customer.name",
					component: "select",
					span: 12,
					options: {
						change: true,
						remote: {
							api: `${this.$CONFIG.API_URL}/customer/main`,
						},
						items: [],
						placeholder: "请输入姓名",
					},
					rules: [
						{required: true, message: "请输入姓名", trigger: "blur"}
					]
				},
				{
					label: "电话",
					name: "customer.contact",
					component: "input",
					span: 12,
					options: {
						placeholder: "请输入电话",
					}
				},
				{
					label: "地址",
					name: "customer.address",
					component: "input",
					options: {
						placeholder: "请输入地址"
					}
				},
				{
					label: "收购信息",
					component: "title",
				},
				{
					label: "品级",
					labelWidth: '100px',
					name: "leafLevel",
					component: "select-only",
					span: 12,
					options: {
						remote: {
							api: `${this.$CONFIG.API_URL}/dict/group`,
							data: {"type":"leaf_level"}
						},
						items: [],
						placeholder: "请选择"
					}
				},
				{
					label: "重量：斤",
					labelWidth: '100px',
					name: "leafAmount",
					component: "number",
					span: 12,
					options: {
						step: 0.01,
						placeholder: "请输入"
					}
				},
				{
					label: "单价：元",
					name: "leafPrice",
					labelWidth: '100px',
					component: "number",
					span: 12,
					options: {
						step: 0.01,
						placeholder: "请输入"
					}
				},
				{
					label: "实际支付：元",
					name: "actualTotalPrice",
					labelWidth: '100px',
					component: "number",
					options: {
						step: 0.01,
						placeholder: "请输入"
					}
				},
				{
					label: "备注",
					name: "leafRemark",
					labelWidth: '100px',
					component: "input",
					options: {
						rows: 3,
						type: "textarea",
						placeholder: "请输入"
					}
				},
				{
					label: "附件",
					labelWidth: '100px',
					name: "attachment",
					component: "multipleImage",
					buttonTip: "附件上传",
					maxSize: 1,
					limit: 3,
					tip: "最多上传3个文件,单个文件不要超过10M",
					options: {
						items: [
							{
								name: "attachment",
								label: "adsadsa"
							}
						]
					}
				}
			]
		}
		// setTimeout(()=>{
		// 	this.config = config
		// },500)
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		async submit() {
			console.info(this.$refs.dialogForm)
			var valid = await this.$refs.dialogForm.validate().catch(() => {
			})
			if (!valid) {
				return false
			}
			this.isSaveing = true;
			if (this.mode === 'add') {
				await this.add()
			} else if (this.mode === 'edit') {
				await this.edit()
			}
			this.isSaveing = false;
		},
		async add() {
			// 调用save方法
			this.$TOOL.response(await this.$API.factory.demo3.insert.post(this.convertToMultiLevelProperty(this.form)),
				() => {
					this.$emit('success', this.form, this.mode)
					this.visible = false;
				})
		},
		async edit() {
			// 调用update方法
			this.$TOOL.response(await this.$API.factory.demo3.update.post(this.convertToMultiLevelProperty(this.form)),
				() => {
					this.$emit('success', this.form, this.mode)
					this.visible = false;
				}, () => {

				})
		},
		convertToMultiLevelProperty(obj) {
			const result = {};

			for (const key in obj) {
				if (Object.prototype.hasOwnProperty.call(obj, key)) {
					const parts = key.split('.');
					let currentObj = result;

					for (let i = 0; i < parts.length - 1; i++) {
						const part = parts[i];

						if (!currentObj[part]) {
							currentObj[part] = {};
						}

						currentObj = currentObj[part];
					}

					currentObj[parts[parts.length - 1]] = currentObj[parts[parts.length - 1]] == null ? obj[key] : currentObj[parts[parts.length - 1]];
				}
			}
			return result;
		},
		flattenObject(obj, parentKey = '') {
			let result = {};
			for (let key in obj) {
				if (Object.prototype.hasOwnProperty.call(obj, key)) {
					let newKey = parentKey ? `${parentKey}.${key}` : key;
					if (typeof obj[key] === 'object' && obj[key] !== null) {
						// 递归处理嵌套对象
						Object.assign(result, this.flattenObject(obj[key], newKey));
					} else {
						result[newKey] = obj[key];
					}
				}
			}
			return result;
		},
		//表单注入数据
		setData(data) {
			// this.form.id = data.id
			// this.form.name = data.name
			// this.form.sex = data.sex
			// this.form.email = data.email
			// this.form.num = data.num

			//可以和上面一样单个注入，也可以像下面一样直接合并进去
			Object.assign(this.form, this.flattenObject(data))
		},
		clearPropertiesWithPrefix(obj, prefix) {
			// 遍历对象的所有可枚举属性
			Object.keys(obj).forEach(key => {
				// 检查属性名是否以指定前缀开头
				if (key.startsWith(prefix)) {
					// 清除属性值，这里将其设为 null
					obj[key] = null;
				}
			});
		},
		onSelected(re) {
			let selected = null
			// 遍历找到对应的选项
			for (let item of this.config.formItems) {
				if (item.name === 'customer.name') {
					for (let option of item.options.items) {
						if (option.label === re) {
							selected = option
						}
					}
				}
			}
			// 客户信息根据前缀置空
			this.clearPropertiesWithPrefix(this.form, "customer.")
			// 级联更新数据
			let merge = {
				'customer.name': selected != null ? selected.label : re,
				'customer.id': selected != null ? selected.id : null,
				'customerId': selected != null ? selected.id : null,
				'customer.contact': selected != null ? selected.contact : null,
				'customer.address': selected != null ? selected.address : null,
			};
			// 重新赋值
			Object.assign(this.form, merge)
		}
	}
}
</script>

<style>
</style>

<!--<template>-->
<!--	<el-autocomplete-->
<!--		v-model="input"-->
<!--		:fetch-suggestions="search"-->
<!--		placeholder="请输入内容"-->
<!--		@select="handleSelect"-->
<!--	></el-autocomplete>-->
<!--</template>-->

<!--<script>-->
<!--export default {-->
<!--	data() {-->
<!--		return {-->
<!--			input: '',-->
<!--			dataList: [-->
<!--				{ value: '选项1' },-->
<!--				{ value: '选项2' },-->
<!--				// 其他选项...-->
<!--			]-->
<!--		};-->
<!--	},-->
<!--	methods: {-->
<!--		// 根据用户输入搜索数据集中的数据-->
<!--		search(queryString, cb) {-->
<!--			let results = [];-->
<!--			if (queryString) {-->
<!--				results = this.dataList.filter(item => {-->
<!--					return item.value.toLowerCase().includes(queryString.toLowerCase());-->
<!--				});-->
<!--			}-->
<!--			// 调用回调函数返回建议列表的数据-->
<!--			cb(results);-->
<!--		},-->
<!--		// 选择下拉列表中的选项时-->
<!--		handleSelect(item) {-->
<!--			console.log('选中的数据：', item);-->
<!--		}-->
<!--	}-->
<!--};-->
<!--</script>-->
